package com.zwz.parse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.util.StringUtils;
import com.zwz.alLayer.ShareholderUtil;
import com.zwz.conf.ContactParserConfig;
import com.zwz.entity.*;
import com.zwz.model.*;
import com.zwz.model.EnterpriseInfo;
import com.zwz.model.Trademark;
import com.zwz.model.basic.BranchCompany;
import com.zwz.model.basic.ChangeRecord;
import com.zwz.model.basic.LegalRepresentative;
import com.zwz.model.known.Patent;
import com.zwz.model.product.SoftwareCopyright;
import com.zwz.model.riskInfo.Member;
import com.zwz.model.riskInfo.TaxpayerInfo;
import com.zwz.model.tendering.AmountStat;
import com.zwz.preProcessArea.Format;
import com.zwz.resp.*;
import com.zwz.resp.BidResponse;
import com.zwz.resp.CompanyInfo;
import com.zwz.resp.annualReports.*;

import com.zwz.resp.maininfo.JudicialCaseResponse;
import com.zwz.resp.product.BiddingResponse;
import com.zwz.resp.riskInfo.AnomalyEntry;
import com.zwz.resp.riskInfo.EnterpriseAnomalyResponse;
import com.zwz.resp.riskInfo.JudicialExecutionResponse;
import com.zwz.resp.weburl.EnterpriseReportWeburl;
import com.zwz.respCompanyDevelopment.ResponseData;
import com.zwz.utils.ConvertWithPrecisionWarning;
import com.zwz.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.zwz.preProcessArea.Utils.*;

@Slf4j
public class JsonParserUtil {


    public static LocalDate safeDateToLocalDate(Date date) {
        return date != null ?
                date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate() :
                null;
    }


    public static com.zwz.entity.EnterpriseInfo parseEnterpriseInfo(String json) {
//        String json = "您的 JSON 字符串";

        ObjectMapper mapper = new ObjectMapper();
//        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 然后使用此mapper进行反序列化

        EnterpriseInfo enterprise = null;
        try {
            enterprise = mapper.readValue(json, EnterpriseInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(null==enterprise){
            log.error("解析数据为空");
        }else{
            // 示例：提取关键字段
            log.info("企业名称: " + enterprise.getName());
            log.info("法定代表人: " + enterprise.getLegalRepresentative());
//            log.info("营业状态："+enterprise.getBusinessTags());
            log.error("测试是否是营业状态" + enterprise.getOperStatus());

            if (null == enterprise.getRegCapital()) {
                log.error("获取RegCapital为空");
            } else {
                log.info("注册资本: " + enterprise.getRegCapital().getValue() + " " +
                        enterprise.getRegCapital().getCoinType());

                log.info("注册资本币种：" + enterprise.getRegCapital().getCoinType());
            }

            //认缴金额没有
            //认缴出资日期
//            实缴资本
            log.info("实缴资本:");

            // 访问深度嵌套字段如注册地址
            log.info("\n注册地址:");
            Address addr = enterprise.getAddressValue();
            if(null==addr){
                addr=new Address();
                addr.setCity("未知");
                addr.setDistrict("未知");
                addr.setProvince("未知");
                addr.setSubdistrict("未知");
                addr.setValue("未知");
            }else{
                log.info(addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getValue());
            }


            //详细地址没有

            //所属行业
            if(null!=enterprise.getIndustry_qcc()){
                log.info("所属行业:" + enterprise.getIndustry_qcc().getFirstIndustry() + " " + enterprise.getIndustry_qcc().getSecondIndustry() + " " + enterprise.getIndustry_qcc().getValue());
            }else{
                IndustryQCC bean = InitDefalutQCC();
                enterprise.setIndustry_qcc(bean);
            }

            //经营范围

//           log.info("经营范围:"+);

            log.info("企业类型（工商登记）" + enterprise.getEnterpriseType());
            log.info("机构类型：" + enterprise.getInstitutionTypes());
            //国有企业

//           log.info("曾用名："+enterprise.);
            //吊销时间
            //注销时间
//            有无营业执照
            log.info("营业执照号" + enterprise.getRegNumber());
            //作废说明

            // 遍历业务标签
            log.info("\n业务标签范围:");
            StringBuffer tag2=new StringBuffer();
            String tag1=null;
            if(org.springframework.util.StringUtils.isEmpty(tag1)){

            }else{
                for (String tag : enterprise.getBusinessTags()) {
                    log.info("- " + tag);
//                    tag1+=tag;
                    tag2.append(tag);
                }
            }


// 直接使用 Date 类型字段
            java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());

// 方法1: 使用 toLocalDate() （JDK 8+）
            LocalDate localDate = sqlDate.toLocalDate();

// 方法2: 通过字符串转换
            LocalDate localDate2 = LocalDate.parse(sqlDate.toString());

            LocalDate d1=null;
//        LocalDateTime dateTime1 = LocalDateTime.parse(enterprise.getFoundTime());
            if(null==enterprise.getFoundTime()){

            }else{
                Date date = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date = sdf.parse(enterprise.getFoundTime());
//           log.info(date); // 输出: Thu Oct 05 00:00:00 CST 2023
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                 d1 = safeDateToLocalDate(date);
            }





            //构造对应的实体bean
            com.zwz.entity.EnterpriseInfo e = new com.zwz.entity.EnterpriseInfo();
            Long i = 0L;
            e.setId(i++);
            e.setCompanyName(enterprise.getName());
            e.setCompanyProfile("");
            e.setEstablishDate(d1);
            e.setBusinessStatus(enterprise.getOperStatus());
            e.setRegisteredCapital(new BigDecimal(0.0));

//            e.setSubscribedCapital(new BigDecimal(enterprise.getRegCapital().getValue()));
            // 调用
            if(null==enterprise.getRegCapital()){
                e.setSubscribedCapital(new BigDecimal(BigInteger.ZERO));
            }else{
                e.setSubscribedCapital(new BigDecimal(enterprise.getRegCapital().getValue()));
                e.setCurrencyType(enterprise.getRegCapital().getCoinType());
            }

            e.setPaidInCapital(new BigDecimal(0.0));
            e.setSubscriptionDate(localDate);
            e.setRegisteredAddress(addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getValue());
            e.setDetailAddress(addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getValue());
            e.setIndustryCategory(enterprise.getIndustry_qcc().getFirstIndustry() + " " + enterprise.getIndustry_qcc().getSecondIndustry() + " " + enterprise.getIndustry_qcc().getValue());
//            e.setBusinessScope(tag1);
            e.setBusinessScope(tag2.toString());
            e.setCompanyType(enterprise.getEnterpriseType());
            e.setInstitutionType("");
            e.setIsStateOwned(true);
            e.setFormerNames("");
            e.setRevocationDate(localDate.plusYears(100));  //这里应该转换判断，默认加个100
            e.setCancellationDate(localDate.plusYears(100)); //这里转换，只要开业，默认加个100
            e.setHasBusinessLicense(true);
            e.setAbolishDeclaration("");
            e.setCreatedAt(localDate);
            e.setUpdatedAt(localDate);
            return e;
        }


        return null;
    }



    public static OfficialWebsiteInfo parseWebUrl(String json) {
//        String json = "您的 JSON 字符串";

        ObjectMapper mapper = new ObjectMapper();
//        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 然后使用此mapper进行反序列化

        EnterpriseInfo enterprise = null;
        try {
            enterprise = mapper.readValue(json, EnterpriseInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(null==enterprise){

            return null;
        }else{
            String homepage = enterprise.getHomepage();

            //构造对应的实体bean
            OfficialWebsiteInfo websiteInfo = new OfficialWebsiteInfo();
            websiteInfo.setWebsiteUrl(homepage);
            int id = 0;
            websiteInfo.setId(Math.toIntExact(id++));
            websiteInfo.setWebsiteUrl(homepage);
            websiteInfo.setHasIcpRecord(false);//默认查不到
            websiteInfo.setIcpRecordCount(0);//默认查不到
            websiteInfo.setIcpRecordDate(new Date());//默认使用ICP的时间
            websiteInfo.setIpOperationNode(null);
            websiteInfo.setIpPhysicalLocation(null);

            websiteInfo.setCreatedAt(new Date());
            websiteInfo.setUpdatedAt(new Date());
            return websiteInfo;
        }



    }


    public static void ParseComDevelopment(String json) {
//        String json = "你的JSON字符串";

        ObjectMapper mapper = new ObjectMapper();
        try {
            ResponseData response = mapper.readValue(json, ResponseData.class);

            // 示例：提取数据
           log.info("Stat: " + response.getStat());
           log.info("ID: " + response.getId());

            // 遍历 fpMembers
            for (FpMember member : response.getFpMembers()) {
               log.info("成员名称: " + member.getMemberName());
               log.info("职位: " + member.getMemberPosition());
            }

            // 遍历 fpSimilars
            for (FpSimilar similar : response.getFpSimilars()) {
               log.info("项目名称: " + similar.getProjectName());
               log.info("企业名称: " + similar.getEnterpriseName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //解析税务
    public static void ParseTax(String json) {
//        String json = "{\"stat\":1,\"total\":2,\"tpCreditRatingList\":[{\"grade\":\"A\",\"year\":\"2021\"},{\"grade\":\"A\",\"year\":\"2020\"}]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析 JSON
            TaxCreditResponse response = mapper.readValue(json, TaxCreditResponse.class);

            // 提取数据示例
           log.info("状态码: " + response.getStat());
           log.info("总记录数: " + response.getTotal());

            // 遍历信用评级
            for (TaxCreditGrade rating : response.getCreditRatings()) {
               log.info("年份: " + rating.getYear() + " | 评级: " + rating.getGrade());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static void ParseAddress(String json) {
//        String json = "{\"stat\":1,\"data\":{...}}"; // 替换为实际 JSON 字符串

        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析 JSON
            InvoiceResponse response = mapper.readValue(json, InvoiceResponse.class);

            // 提取数据示例
           log.info("状态码: " + response.getStat());
           log.info("企业名称: " + response.getData().getName());

            // 输出地址信息
            Address addr = response.getData().getAddress();
           log.info("注册地址: " + addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getValue());

            // 遍历业务标签
           log.info("业务标签:");
            for (String tag : response.getData().getBusinessTags()) {
               log.info("- " + tag);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void pasreProduct(String json) {
//        String json = "{\"stat\":1,\"total\":1,\"data\":[{\"brandImageLink\":\"https:\\/\\/image.maigoo.com\\/upload\\/images\\/20210930\\/11220335057_207x90.gif\",\"brandSetTime\":\"2010年\",\"brandDesc\":\"南京希玛格节能科技有限公司是位于南京市江宁开发区的高新技术企业...\",\"brandName\":\"希玛格\",\"_id\":\"uVWat6f\\/7CQ=\",\"brandCradle\":\"南京市\"}]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析 JSON
            BrandResponse response = mapper.readValue(json, BrandResponse.class);

            // 提取数据示例
           log.info("状态码: " + response.getStat());
           log.info("总记录数: " + response.getTotal());

            // 遍历品牌数据
            for (BrandData brand : response.getData()) {
               log.info("\n品牌名称: " + brand.getName());
               log.info("成立时间: " + brand.getSetTime());
               log.info("发源地: " + brand.getCradle());
               log.info("品牌描述: " + brand.getDescription().substring(0, 50) + "..."); // 截取前50字符
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void parseRisk(String json) {
//        String json = "{\"stat\":1,\"name\":\"南京希玛格节能科技有限公司\",\"annualRiskStatsNew\":{\"2025\":{\"法律风险\":2,\"经营风险\":0}},\"socialCreditCode\":\"91320102562886704M\",\"riskTypeStatsNew\":{\"法律风险\":2,\"经营风险\":0},\"legalRepresentative\":\"穆宏志\",\"regNumber\":\"320104000106568\",\"_id\":\"577de19eadf21dc4\",\"businessTags\":[\"节能项目技术咨询\",\"配套机电设备维护\",\"中央空调销售\",\"锅炉安装\",\"配套机电设备保养\",\"中央空调调试\",\"配套机电设备销售\",\"配套机电设备调试\",\"能源管理系统安装\",\"机电设备安装\",\"电力管理系统设计\",\"电力管理系统安装\",\"电力管理系统调试\",\"锅炉维护保养\",\"能源管理系统调试\",\"电力管理系统维护\",\"节能产品开发制造\",\"能源管理系统设计\",\"系统软件开发集成\",\"节能项目施工\",\"中央空调维护\",\"电力管理系统技术服务\",\"中央空调保养\",\"能源管理系统技术服务\",\"节能项目设计\",\"锅炉设计\",\"锅炉销售\",\"合同能源管理\",\"能源管理系统维护\",\"节能项目运营管理服务\"]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析 JSON
            CompanyInfo company = mapper.readValue(json, CompanyInfo.class);

            // 提取数据示例
           log.info("企业名称: " + company.getName());
           log.info("统一社会信用代码: " + company.getSocialCreditCode());
           log.info("法定代表人: " + company.getLegalRepresentative());

            // 输出 2025 年风险数据
            RiskStats stats2025 = company.getAnnualRiskStats().get("2025");
           log.info("\n2025年风险统计:");
           log.info("法律风险: " + stats2025.getLegalRisk());
           log.info("经营风险: " + stats2025.getOperationalRisk());

            // 输出风险类型统计
           log.info("\n风险类型统计:");
           log.info("法律风险: " + company.getRiskTypeStats().getLegalRisk());
           log.info("经营风险: " + company.getRiskTypeStats().getOperationalRisk());

            // 遍历业务标签
           log.info("\n业务标签:");
            for (String tag : company.getBusinessTags()) {
               log.info("- " + tag);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void parseEnterpriseRisk(String json) {
//        String json = "{\"stat\":1,\"anomalyList\":[],\"name\":\"南京希玛格节能科技有限公司\",\"entity_type\":\"enterprise\",\"socialCreditCode\":\"91320102562886704M\",\"legalRepresentative\":\"穆宏志\",\"regNumber\":\"320104000106568\",\"_id\":\"577de19eadf21dc4\",\"nameId\":\"577de19eadf21dc4\",\"businessTags\":[\"节能项目技术咨询\",\"配套机电设备维护\",\"中央空调销售\",\"锅炉安装\",\"配套机电设备保养\",\"中央空调调试\",\"配套机电设备销售\",\"配套机电设备调试\",\"能源管理系统安装\",\"机电设备安装\",\"电力管理系统设计\",\"电力管理系统安装\",\"电力管理系统调试\",\"锅炉维护保养\",\"能源管理系统调试\",\"电力管理系统维护\",\"节能产品开发制造\",\"能源管理系统设计\",\"系统软件开发集成\",\"节能项目施工\",\"中央空调维护\",\"电力管理系统技术服务\",\"中央空调保养\",\"能源管理系统技术服务\",\"节能项目设计\",\"锅炉设计\",\"锅炉销售\",\"合同能源管理\",\"能源管理系统维护\",\"节能项目运营管理服务\"]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            com.zwz.model.CompanyInfo company = mapper.readValue(json, com.zwz.model.CompanyInfo.class);

            // 打印关键信息
           log.info("企业名称: " + company.getName());
           log.info("法定代表人: " + company.getLegalRepresentative());
           log.info("统一社会信用代码: " + company.getSocialCreditCode());
           log.info("业务标签数量: " + company.getBusinessTags().size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void ParseCourt(String json) {
//        String json = "{...}"; // 替换为实际JSON字符串

        ObjectMapper mapper = new ObjectMapper();
        try {
            LegalCaseResponse response = mapper.readValue(json, LegalCaseResponse.class);

            // 打印关键信息
           log.info("状态码: " + response.getStat());
           log.info("总案件数: " + response.getTotal());
           log.info("----------------------");

            // 遍历所有案件
            for (CaseInfo caseInfo : response.getData()) {
               log.info("案件ID: " + caseInfo.getId());
               log.info("案由: " + caseInfo.getCaseReason());
               log.info("开庭时间: " + caseInfo.getCaseDate());
               log.info("发布单位: " + caseInfo.getPublishUnit());

                // 打印原告信息
               log.info("原告列表:");
                for (Plaintiff plaintiff : caseInfo.getPlaintiffList()) {
                   log.info(" - 名称: " + plaintiff.getName());
                   log.info(" - 实体类型: " + plaintiff.getEntityType());
                }
               log.info("----------------------");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void parseTaxPayer(String json) {
//        String json = "..."; // 用户提供的JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        try {
            com.zwz.model.riskInfo.CompanyInfo company = mapper.readValue(json, com.zwz.model.riskInfo.CompanyInfo.class);
            // 打印解析结果
           log.info("Stat: " + company.getStat());
           log.info("ID: " + company.getId());
            List<Member> member = company.getMembers();
            for (Member m : company.getMembers()) {
               log.info("Member: " + m.getMemberName());
            }

//            List<SimilarProject> p= company.getSimilarProjects();
//
//            for (SimilarProject  p : company.getSimilarProjects()) {
//               log.info("Project: " + p.getProjectName());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //解析
    public static void parseTaxPayer2(String json) {
//        String json = "{\"stat\":1,\"_id\":\"V33hnq3yHcQ=\",\"tpStatusUpdateTime\":\"2025-02-24\",\"tpAnomalyRegisterDate\":null,\"tpStatus\":\"正常\",\"tpStatusChangeTime\":null,\"tpId\":\"91320102562886704M\",\"revenuePunishmentList\":[],\"tpOwingTaxFullList\":[],\"tpIllegalList\":[],\"tpHistoryStateList\":[],\"recordDate\":\"2025-02-24\",\"tpBusinessAddress\":null,\"tpStateList\":[],\"tpName\":\"南京希玛格节能科技有限公司\"}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            TaxpayerInfo info = mapper.readValue(json, TaxpayerInfo.class);

            // 输出关键信息
           log.info("状态码: " + info.getStat());
           log.info("纳税人名称: " + info.getName());
           log.info("统一社会信用代码: " + info.getTaxpayerId());
           log.info("状态: " + info.getStatus());
           log.info("最后更新时间: " + info.getStatusUpdateTime());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static List<com.zwz.entity.Trademark> parseKnown(String json) {
//        String json = "{\"status\":[0],\"tmStatusNew\":[\"等待实质审查\"],\"stat\":1, ... }"; // 完整JSON

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            TrademarkResponse response = mapper.readValue(json, TrademarkResponse.class);

            // 输出关键信息
           log.info("商标总数: " + response.getTotal());
           log.info("当前状态统计: " + response.getTmStatusStat());


             List<com.zwz.entity.Trademark> list=new ArrayList<>();

           //构建对应的入库信息
            com.zwz.entity.Trademark t=null;

            // 遍历商标信息
            for (Trademark tm : response.getTrademarks()) {
               log.info("\n商标名称: " + tm.getName());
               log.info("注册号: " + tm.getRegNumber());
               log.info("分类："+tm.getAgentName());
               log.info("服务内容:");
               for (TmServiceContent content : tm.getServiceContents()) {
                    System.out.printf("- 代码: %s -分类：%s| 详情: %s%n",
                            content.getCode(),
                            content.getInternationalClass(),
                            content.getDetail());
                }
                t   =new  com.zwz.entity.Trademark();
               t.setAddress(tm.getAddress());
               t.setCompanyName(t.getCompanyName());
               t.setAgentName(t.getAgentName());
               t.setAgentNameId(t.getAgentNameId());
               t.setNameId(tm.getNameId());
               t.setImageUrl(tm.getImageUrl());
               t.setStatusCode(tm.getStatusCode());
               t.setRegNumber(tm.getRegNumber());
               t.setStatusNew(tm.getStatusNew());
               t.setSingleAppTime(tm.getApplicationTime());
               if(StringUtils.isNullOrEmpty(tm.getName())){
                   t.setName("未知");
               }else{
                   t.setName(tm.getName());
               }


               //就这些吧
                list.add(t);

            }

            return list;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void parsePatent(String jsonResponse) {
//        String jsonResponse = "..."; // 你的JSON字符串

        ObjectMapper mapper = new ObjectMapper();
        try {
            PatentResponse response = mapper.readValue(jsonResponse, PatentResponse.class);
            // 处理解析后的数据
           log.info("Total Patents: " + response.getPatentNumber());
            for (Patent patent : response.getPatents()) {
               log.info("Patent Name: " + patent.getPatentName());
               log.info("Inventors: " + patent.getPatentInventor());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void ParseTending(String json) {
//        String json = "你的JSON字符串";

        ObjectMapper mapper = new ObjectMapper();
        try {
            BidResponse response = mapper.readValue(json, BidResponse.class);

            // 示例数据访问
           log.info("总状态码: " + response.getStat());
           log.info("数据库ID: " + response.getData().getId());

            // 遍历金额分布统计
            for (AmountStat stat : response.getData().getAmountStats()) {
                System.out.printf("区间: %s, 占比: %.2f%%, 中标次数: %d%n",
                        stat.getRangeScope(),
                        stat.getPercentage(),
                        stat.getCount());
            }

            // 访问其他统计数据同理...

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static List<EnterpriseAnnualReport> parseAnnualReport(String json) {
//        String json = "你的JSON字符串";

        ObjectMapper mapper = new ObjectMapper();
//        mapper.registerModule(new JavaTimeModule());  // 支持日期类型 todo 入库时放开
        List<EnterpriseAnnualReport> annualReportlist = new ArrayList<>();

        EnterpriseAnnualReport annualReport;
        //1.构建年报信息
        annualReport = new EnterpriseAnnualReport();
        try {
            com.zwz.resp.annualReports.BidResponse response = mapper.readValue(json, com.zwz.resp.annualReports.BidResponse.class);


            //构建对应的联系方式信息


            // 示例数据访问
           log.info("总记录数: " + response.getTotalRecords());
           log.info("显示总数: " + response.getDisplayTotal());

            for (BidRecord record : response.getBidRecords()) {
               log.info("\n项目标题: " + record.getProjectTitle());
                System.out.printf("地区: %s %s%n",
                        record.getBidRegion().getProvince(),
                        record.getBidRegion().getCity());

                if (record.getContractValue() != null) {
                    System.out.printf("合同金额: ¥%.2f万%n", record.getContractValue());
                }


//                //构建新的固话和邮箱地址
//                String tel = record.getClientId();
//                String email=record.getClientName();
//
//              AccountInfo  accountInfo  =new AccountInfo();
//              accountInfo.setTel(tel);
//             accountInfo.setEmail(email);


                int i = 0;
                annualReport.setId(i++);

                Date yeardate = record.getAnnouncementDate();
                int year = getYearFromDate(yeardate);

                annualReport.setReportYear(year);
                annualReport.setInsuredCount(0);//默认是0
                annualReport.setAddress(record.getClientAddress().toString());
                annualReport.setHasReport(true); //需要逻辑判断
                annualReport.setForeignInvestment("false"); //默认false
//                annualReport.setTaxAmount(new BigDecimal( record.getContractValue()    )); //合同金额
                annualReport.setTaxAmount(record.getContractValue() != null ? new BigDecimal(record.getContractValue().toString()) : BigDecimal.ZERO);
                annualReport.setTotalAssets(new BigDecimal(""));//资产总额
                annualReport.setTotalRevenue(new BigDecimal("0.0")); //营业总收入
                annualReport.setNetProfit(new BigDecimal(("0.0"))); //净利润
                annualReport.setTotalLiabilities(new BigDecimal("0.0"));
                annualReport.setTotalLiabilities(new BigDecimal("0.0")); //负债总额
                annualReport.setLastUpload(new Date());
                annualReport.setHasReport(true);
                annualReport.setCreatedAt(new Date());
                annualReport.setUpdatedAt(new Date());

                annualReportlist.add(annualReport);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return annualReportlist;
    }


    public static List<AccountInfo> parseEmailAndAddress(String json) throws IOException {
//        String json = "你的JSON字符串";

        ObjectMapper mapper = new ObjectMapper();
//        mapper.registerModule(new JavaTimeModule());  // 支持日期类型 todo 入库时放开
        List<AccountInfo> accountInfolist = new ArrayList<>();


        com.zwz.resp.annualReports.BidResponse response = mapper.readValue(json, com.zwz.resp.annualReports.BidResponse.class);


        //构建对应的联系方式信息

        // 示例数据访问
       log.info("总记录数: " + response.getTotalRecords());
       log.info("显示总数: " + response.getDisplayTotal());
        AccountInfo accountInfo = new AccountInfo();
        for (BidRecord record : response.getBidRecords()) {
            //构建新的固话和邮箱地址
            String tel = record.getClientId();
            String email = record.getClientName();

            accountInfo.setTel(tel);
            accountInfo.setEmail(email);

            accountInfolist.add(accountInfo);

        }


        return accountInfolist;

    }


    public static int getYearFromDate(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("Date cannot be null");
        }
        Instant instant = date.toInstant();
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate.getYear();
    }


    public static void parseContact(String json) {
//        String json = "您的原始JSON数据";

        try {
            EnterpriseContactResponse response = ContactParserConfig.parse(json);

            // 分析企业信息
           log.info("企业名称: " + response.getEnterpriseLead().getCompanyName());
           log.info("注册时间: " + response.getEnterpriseLead().getRegistrationDate());

            // 遍历核心联系人
            for (ContactProfile contact : response.getTopContacts()) {
               log.info("\n联系人: " + contact.getDisplayLabel());
               log.info("最新检测: " + contact.getLastDetectionDate());

                // 分析联系渠道
                for (ContactChannel channel : contact.getChannels()) {
                    System.out.printf("渠道类型: %-8s 平台: %s%n",
                            channel.getChannelType(),
                            channel.getSourcePlatform());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static InvestmentEmploymentInfo ParseCopmpany(String json) {
//        String json = "您的JSON数据";

        ObjectMapper mapper = new ObjectMapper();
        try {
            CompanyResponse response = mapper.readValue(json, CompanyResponse.class);

            // 访问数据示例
           log.info("总记录数: " + response.getTotalRecords());

            for (BranchCompany branch : response.getBranchCompanies()) {
               log.info("\n分支机构名称: " + branch.getName());
               log.info("成立时间: " + branch.getEstablishmentDate());

                com.zwz.model.basic.Address addr = branch.getAddress();
                System.out.printf("详细地址: %s %s %s%n",
                        addr.getProvince(),
                        addr.getCity(),
                        addr.getDistrict());

                LegalRepresentative legal = branch.getLegalRepresentative();
               log.info("法人代表: " + legal.getLegalPersonName());
            }


            // 直接使用 Date 类型字段
            java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());

// 方法1: 使用 toLocalDate() （JDK 8+）
            LocalDate localDate = sqlDate.toLocalDate();


            String date = DateUtil.now();


            LocalDateTime localDateTime = LocalDateTime.now();
            Date curDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

            //构建实体bean 并返回
            InvestmentEmploymentInfo invest = new InvestmentEmploymentInfo();
            int i = 0;
            invest.setId(i++);
            List<BranchCompany> list = response.getBranchCompanies();
            StringBuffer sb=new StringBuffer();
            for(int k=0;k< list.size();k++){
                sb.append(list.get(k));
            }


            invest.setBranchOffices(sb.toString());//设置对应的分支办公室为字符串拼接
            invest.setHasForeignInvestment(false); //默认无外商投资
            invest.setShareholderInfo("test");//股东信息，需要重新抓取
            invest.getLargestShareholderRatio();//最大股东占比
            invest.setShareholderCount(12);//股东人数
            invest.setCreatedAt(curDate);
            invest.setUpdatedAt(curDate);


            return invest;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static List<InformationChange> parseChange(String json) {
//        String json = "您的JSON数据";
        InformationChange change = null;
        List<InformationChange> list=new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        int i = 0;
        //构建的变更信息返回对应的实体bean 信息
        try {
            CompanyChangeResponse response = mapper.readValue(json, CompanyChangeResponse.class);


           log.info("总变更记录数: " + response.getTotalRecords());

            for (ChangeRecord record : response.getChangeHistory()) {
               log.info("\n变更类型: " + record.getChangeType());
               log.info("变更日期: " + record.getChangeDate());

               log.info("变更前:");
                record.getOldValues().forEach(System.out::println);

               log.info("变更后:");
                record.getNewValues().forEach(System.out::println);

                String changestr = null;
                for (int k=0;i<record.getOldValues().size();i++){
                    change = new InformationChange();
                    if (StringUtils.isNullOrEmpty(record.getChangeType())
                            || (record.getChangeType().contains("地址变更"))) {
                        changestr = "地址变更";
                        change.setId(i++);
                        change.setChangeDate(record.getChangeDate());
                        change.setChangeType(changestr); //默认值
                        change.setHasDateChange(true); //根据什么来判断合适

                        //结果集中去除多余的<span></<span>
                        change.setLatestAddress(Format.removeSpanTags(record.getNewValues().get(k))); //最新的地址,需要从外表系统中获取,取最后一条记录
                        change.setPreviousAddress(Format.removeSpanTags(record.getOldValues().get(k))); //取上一个记录

                        change.setCreatedAt(new Date());
                        change.setUpdatedAt(new Date());
                        list.add(change);
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }


    /**
     * 参考逻辑
     *
     * @param json
     * @return
     */
    public static InformationChange parseChange2(String json) {
        if (StringUtils.isNullOrEmpty(json)) {
            throw new IllegalArgumentException("JSON input cannot be null or empty");
        }

        ObjectMapper mapper = new ObjectMapper();
        InformationChange change = new InformationChange();

        try {
            CompanyChangeResponse response = mapper.readValue(json, CompanyChangeResponse.class);
            List<ChangeRecord> addressChanges = response.getChangeHistory().stream()
                    .filter(r -> "地址变更".equals(r.getChangeType()))
                    .sorted((a, b) -> b.getChangeDate().compareTo(a.getChangeDate())) // 按时间倒序
                    .collect(Collectors.toList());

            if (!addressChanges.isEmpty()) {
                // 取最新的地址变更记录
                ChangeRecord latestChange = addressChanges.get(0);

                // 处理地址变更
                if (!latestChange.getNewValues().isEmpty()) {
                    change.setLatestAddress(latestChange.getNewValues().get(0));
                }
                if (!latestChange.getOldValues().isEmpty()) {
                    change.setPreviousAddress(latestChange.getOldValues().get(0));
                }

                // 设置变更日期
                change.setChangeDate(latestChange.getChangeDate());

                // 判断是否有日期变更
                boolean hasDateChange = addressChanges.stream()
                        .anyMatch(r -> r.getChangeDate() != null);
                change.setHasDateChange(hasDateChange);
            }

            change.setChangeType("地址变更");
            change.setCreatedAt(new Date());
            change.setUpdatedAt(new Date());

        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException("处理变更记录时发生错误", e);
        }

        return change;
    }


    public static List<SoftwareRegistry> ParseSoft(String json) {
//        String json = "您的JSON数据";

        ObjectMapper mapper = new ObjectMapper();
        try {
            SoftwareCopyrightResponse response = mapper.readValue(json, SoftwareCopyrightResponse.class);

            //构造对象
            List<SoftwareRegistry> list=new ArrayList<>();

           log.info("总记录数: " + response.getTotal());
           log.info("本年登记数: " + response.getCurrentYearCount());

            response.getCopyrights().forEach(copyright -> {
               log.info("\n软件名称: " + copyright.getSoftwareFullName());
               log.info("登记号: " + copyright.getRegistrationNumber());
               log.info("版本: " + copyright.getSoftwareVersion());

                if (copyright.getPublicationDate() != null) {
                   log.info("发表日期: " + copyright.getPublicationDate());
                }
            });

            if (response.getCopyrights() == null || response.getCopyrights().isEmpty()) {
                return null;
            }
            SoftwareCopyright copyright=null;
            SoftwareRegistry registry=null;
            for(int i=0;i<response.getCopyrights().size();i++){
                 copyright = response.getCopyrights().get(i);
                 registry = new SoftwareRegistry();
                // 使用BeanUtils进行属性拷贝，提高性能
                BeanUtils.copyProperties(copyright, registry);
                list.add(registry);

            }


            return list;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void parseTm(String json) {
//        String json = "您的JSON数据";

        ObjectMapper mapper = new ObjectMapper();
        try {
            BiddingResponse response = mapper.readValue(json, BiddingResponse.class);

           log.info("总记录数: " + response.getTotal());
           log.info("显示总数: " + response.getDisplayTotal());

            for (BiddingResponse.BiddingProject project : response.getData()) {
               log.info("\n项目ID: " + project.getProjectId());
               log.info("项目标题: " + project.getProjectTitle());
                System.out.printf("招标地区: %s%s %s%n",
                        project.getRegion().getProvince(),
                        project.getRegion().getCity(),
                        project.getRegion().getDistrict() != null ? " " + project.getRegion().getDistrict() : "");

                System.out.printf("合同金额: ¥%.2f万%n", project.getContractAmount());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public static void parseReport(String  json) {
////        String json = "您的JSON数据";
//
//        ObjectMapper mapper = new ObjectMapper();
//        try {
//           com.zwz.resp.annualReports. EnterpriseAnnualReport report = mapper.readValue(json,   com.zwz.resp.annualReports. EnterpriseAnnualReport.class);
//
//            // 访问示例数据
//           log.info("企业ID: " + report.getEnterpriseId());
//           log.info("总年报数: " + report.getTotal());
//
//            report.getAnnualReports().forEach(annual -> {
//               log.info("\n年份: " + annual.getReportYear());
//
//                annual.getBasicInfo().forEach(info -> {
//                    if(info.getName().contains("联系电话")) {
//                       log.info("联系电话: " + info.getValue());
//                    }
//                });
//
//               log.info("股东列表:");
////                annual.getShareholders().forEach(shareholder -> {
////                    System.out.printf("%s 认缴金额: %s%n",
////                            shareholder.getShareholderName(),
////                            shareholder.getSubscribedCapital());
////                });
//            });
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    // 示例使用方法
    public static List<EnterpriseAnnualReport> parseReport3(String json) throws IOException {

        List<EnterpriseAnnualReport> list = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();


//            mapper.readValue(json, BiddingResponse.class);
        EnterpriseReport report = mapper.readValue(json, EnterpriseReport.class);
        EnterpriseAnnualReport e = null;
        // 深度遍历输出所有字段
       log.info("企业ID: " + report.getEnterpriseId());
       log.info("状态码: " + report.getStat());


        if(report!=null && report.getReports()!=null){
            // 遍历所有年报
            for (Report r : report.getReports()) {

                e = new EnterpriseAnnualReport();


               log.info("\n年报ID: " + r.getId());
               log.info("=============================================年份 " + r.getArYear() + "》》》》》》》》》》》》》》》》》》");
               log.info("年份: " + r.getArYear());


                int i = 0;
                e.setId(i++);
                e.setHasReport(true);

                // 输出基本信息
                for (BasicInfo info : r.getArBasic()) {
                   log.info(">>>>>>>>>>>>>>>>>>>>>>>>>");
                    System.out.printf("%s: %s\n", info.getName(), info.getValue());
                    e.setAnnualReport(info.getValue());
                   log.info("测试输出：" + info.getName());
                   log.info("<<<<<<<<<<<<<<<<<<<<<<<");

                }

                e.setReportYear(r.getArYear());
                // 输出社保信息
                SocialSecurity ss = r.getArSocialSecurity();
                if (null != ss) {

                   log.info("失业保险人数: " + ss.getUnemploymentInsuranceNum());
                    if (StringUtils.isNullOrEmpty(ss.getUnemploymentInsuranceNum())) {
                        e.setInsuredCount(0);
                    } else {
                        e.setInsuredCount(Integer.parseInt(ss.getUnemploymentInsuranceNum().substring(0, 1)));
                    }

                   log.info("养老保险基数: " + ss.getOldAgeInsuranceBase());

                }
                e.setHasReport(true);
                e.setForeignInvestment("false");

                // 输出资产信息
//                for (Asset asset : r.getArAssets()) {
//                    System.out.printf("%s: %s\n", asset.getName(), asset.getValue());
//
//                }
//
//                // 输出股东信息
//                for (Holder holder : r.getArHolderList()) {
//                    System.out.printf("股东: %s 认缴金额: %s\n",
//                            holder.getHolder(),
//                            holder.getSubscriptionAmount()
//                    );

                //输出对应的bidres 的方法
//            List<BasicInfo> basic = r.getArBasic();
//                for(int i=0;i<basic.size();){
//
//                }

                //构建实体bean  并返回
                e.setTotalLiabilities(new BigDecimal(0.0));
                e.setCreatedAt(new Date());
                e.setUpdatedAt(new Date());

                //到Vo里找
                e.setForeignInvestment("");

                //直接取出放到mem,需要返回
//
//            com.zwz.vo.ReportInfo   reportInfo= new com.zwz.vo.ReportInfo();
//            reportInfo.setNetSum(1 ); //净利润
//            reportInfo.setCapSum(2);
//            reportInfo.setMangeSum(3);
//            reportInfo.setPureprofit(new BigDecimal(6.0));
//            reportInfo.setTaxSum(6);
//            reportInfo.setMangeSum(7);
//            reportInfo.setCapSum(1);

                list.add(e);

               log.info("=============================================结束年份 " + r.getArYear() + "》》》》》》》》》》》》》》》》》》》》");
            }
        }else {
            System.err.println("get year is null");
        }


        return list;
    }


    // 使用示例
    public static MemInfo ParseShold(String json) {
//        String json = "{\"stat\":1,\"total\":2,\"page\":["
//                + "{\"relatedEnterpriseCurrentNum\":1,\"ratio\":0.5482,"
//                + "\"name\":\"?o??\",\"relatedEnterpriseHistoryNum\":5,"
//                + "\"humanId\":\"b3aba34781bdc90a\",\"position\":[\"??ж?????????\"],"
//                + "\"isController\":1},"
//                + "{\"relatedEnterpriseCurrentNum\":1,\"ratio\":0.4518,"
//                + "\"name\":\"???\",\"relatedEnterpriseHistoryNum\":2,"
//                + "\"humanId\":\"734df1e125e7b4de\",\"position\":[\"????\"]}]}";

        try {
//            EnterpriseReport report = parse(json);
            ObjectMapper mapper = new ObjectMapper();
            com.zwz.resp.basic.EnterpriseReport report = mapper.readValue(json, com.zwz.resp.basic.EnterpriseReport.class);

            //构建实体bean 字段
            MemInfo m = new MemInfo();
            m.setSholdnum((String.valueOf(report.getShareholders().size())));
            m.setMaxShold(ConvertWithPrecisionWarning.convertWithPrecisionWarning(ShareholderUtil.findMaxShareRatio((report.getShareholders()))));


           log.info("股东数量: " + report.getShareholders().size());
//           log.info("=".repeat(40));

            report.getShareholders().forEach(sh -> {
               log.info("股东名称: " + sh.getName());
               //log.info("持股比例: " + new BigDecimal(String.valueOf(sh.getShareRatio())));  这个是null 的
//               log.info("持股比例: " + sh.getShareRatio.multiply(new BigDecimal(100)) + "%");

               log.info("关联企业: 当前" + sh.getCurrentEnterprises()
                        + "家，历史" + sh.getHistoryEnterprises() + "家");
//               log.info("-".repeat(30));




            });


            return m;

        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }


    //接下对应的email 和 地址的方法
    // 示例使用方法
    public static AccountInfo parseReport4(String json) throws IOException {

        List<EnterpriseAnnualReport> list = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        AccountInfo accountInfo = new AccountInfo();

        EnterpriseReport report = mapper.readValue(json, EnterpriseReport.class);
        EnterpriseAnnualReport e = null;
        // 深度遍历输出所有字段
       log.info("企业ID: " + report.getEnterpriseId());
       log.info("状态码: " + report.getStat());


        // 遍历所有年报
        for (Report r : report.getReports()) {

            e = new EnterpriseAnnualReport();


           log.info("\n年报ID: " + r.getId());
           log.info("=============================================年份 " + r.getArYear() + "》》》》》》》》》》》》》》》》》》");
           log.info("年份: " + r.getArYear());


            int i = 0;
            e.setId(i++);
            e.setHasReport(true);


            String tel = null;
            String email = null;
            // 输出基本信息
            for (BasicInfo info : r.getArBasic()) {
               log.info(">>>>>>>>>>>>>>>>>>>>>>>>>");
                System.out.printf("%s: %s\n", info.getName(), info.getValue());
                e.setAnnualReport(info.getValue());
               log.info("测试输出：" + info.getName());

                //todo 解析的方式不对，待优化
                if ("企业联系电话".equals(info.getName())) {
                    //构建新的固话和邮箱地址
                    tel = info.getValue();

                    //这里区分手机和固化，如果是1开头的全部当做手机否则都是固化
                    if(tel.startsWith("1")){
                        accountInfo.setTel(tel);
                    }else{
                        accountInfo.setLandline(tel);
                    }

                }
                if ("企业电子邮箱".equals(info.getName())) {
                    email = info.getValue();
                }
               log.info("<<<<<<<<<<<<<<<<<<<<<<<");



                accountInfo.setEmail(email);

            }



            //引入预处理层 ，todo 待jsr 拦截
//            if(Validator.isValidChineseMobile(tel) ){
//
//            }



           log.info("=============================================结束年份 " + r.getArYear() + "》》》》》》》》》》》》》》》》》》》》");
        }
        return accountInfo;
    }


    // 解析执行方法
    public static EnterpriseReportWeburl parse(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, EnterpriseReportWeburl.class);
    }

    // 示例用法
    public static WebUrl parseWeburl(String json) throws Exception {
//        String json = "您的完整JSON数据";

        EnterpriseReportWeburl report = parse(json);

       log.info("企业名称: " + report.getCompanyName());
       log.info("主要域名: " + report.getCleanDomain());
       log.info("响应时间: " + report.getSafeResponseTime() + "s");
        AtomicReference<Date> tt;
        WebUrl w = new WebUrl();
        report.getIcpRecords().forEach(icp -> {
           log.info("ICP备案号: " + icp.getIcpNumber()
                    + " 审核日期: " + icp.getAuditDate());
            w.setTime(icp.getAuditDate());
        });

        //深入解析节点信息
        List<EnterpriseReportWeburl.DomainInfo> domain = report.getDomains();
        for (int k = 0; k < domain.size(); k++) {

            //todo 待优化，多了有Bug

            if (domain.get(k).getIpAddresses() != null && domain.get(k).getIpAddresses().size() == 1) {
                EnterpriseReportWeburl.DomainInfo.IPAddress addess = domain.get(k).getIpAddresses().get(0);
                w.setNode(addess.getIp());
                w.setLcoation(addess.getLocation());
            }
        }


//            w.setNode(i);


        return w;
    }


    //接下对应的email 和 地址的方法
    // 示例使用方法
    public static List<ReportInfo> parseReport5(String json) throws IOException {

        List<EnterpriseAnnualReport> list = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        AccountInfo accountInfo = new AccountInfo();

        EnterpriseReport report = mapper.readValue(json, EnterpriseReport.class);
        EnterpriseAnnualReport e = null;
        // 深度遍历输出所有字段
       log.info("企业ID: " + report.getEnterpriseId());
       log.info("状态码: " + report.getStat());

        List<ReportInfo> res = new ArrayList<>();
        ReportInfo re = null;

        if( report.getReports()!=null){
            // 遍历所有年报
            for (Report r : report.getReports()) {

                e = new EnterpriseAnnualReport();


               log.info("\n年报ID: " + r.getId());
               log.info("=============================================年份 " + r.getArYear() + "》》》》》》》》》》》》》》》》》》");
               log.info("年份: " + r.getArYear());

                re = new ReportInfo();

                if( null ==r.getArAssets()){
                  log.info("获取资源数据为空");
                }else{
                    // 输出基本信息
                    for (Asset info : r.getArAssets()) {
                        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>");
                        System.out.printf("%s: %s\n", info.getName(), info.getValue());
                        e.setAnnualReport(info.getValue());
                        log.info("测试输出：" + info.getName());


                        String v1 = null;
                        String v2 = null;
                        String v3 = null;
                        String v4 = null;
                        String v5 = null;
                        String v6 = null;

                        //todo 解析的方式不对，待优化
                        if ("纳税金额".equals(info.getName())) {
                            //构建新的固话和邮箱地址
                            v1 = info.getValue();
                            if (isEquals(v1)) {

                            } else {
                                re.setTaxSum(removeLastTwoChinese(v1));
                            }


                        }
                        if ("资产总额".equals(info.getName())) {
                            v2 = info.getValue();
                            if (isEquals(v2)) {
                                re.setTaxSum("0");
                            } else {
                                re.setCapSum(removeLastTwoChinese(v2));
                            }

                        }
                        if ("营业总收入".equals(info.getName())) {
                            v3 = info.getValue();
                            if (isEquals(v3)) {
                                re.setMangeSum("0");
                            } else {
                                re.setMangeSum(removeLastTwoChinese(v3));

                            }


                        }
                        if ("净利润".equals(info.getName())) {
                            v4 = info.getValue();
                            if (isEquals(v4)) {
                                re.setPureprofit("0.0");
                            } else {
                                re.setPureprofit(removeLastTwoChinese(v4));
                            }

                        }
                        if ("利润总额".equals(info.getName())) {
                            v5 = info.getValue();
                            if (isEquals(v5)) {
                                re.setProfitnum("0");
                            } else {
                                re.setProfitnum(removeLastTwoChinese(v5));
                            }
                        }
                        if ("负债总额".equals(info.getName())) {
                            v6 = info.getValue();
                            if (isEquals(v6)) {
                                re.setAboundSum("0");
                            } else {
                                re.setAboundSum(removeLastTwoChinese(v6));
                            }

                        }


                        log.info("<<<<<<<<<<<<<<<<<<<<<<<");

                    }
                }



                res.add(re);

               log.info("=============================================结束年份 " + r.getArYear() + "》》》》》》》》》》》》》》》》》》》》");
            }
        }else{
            System.err.println("get report is null");
        }

        return res;
    }


    // 解析执行方法
    public static com.zwz.resp.bid.BiddingResponse parse1(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        // 允许未知字段
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(json, com.zwz.resp.bid.BiddingResponse.class);
    }

    // 示例用法
    public static List<BidInfo> parsetoubiao(String json) throws IOException {
//        String json = "您的JSON数据";


            com.zwz.resp.bid.BiddingResponse response = parse1(json);

            if(response==null){
                log.error("获取的招标信息为空");
            }else {

                if(null== response.getProjects()){
                    log.error("获取对应的项目数据为空");
                }else{
                    log.info("总项目数: " + response.getProjects().size());
                    log.info("========================");
                    //构建中间聚合字段vo
                    BidInfo b = new BidInfo();
                    List<BidInfo> list = new ArrayList<>();

                    response.getProjects().forEach(project -> {
                        log.info("项目标题: " + project.getCleanTitle());
                        log.info("发布日期: " + project.getPublishDate());
                        log.info("所在地区: " +
                                project.getRegion().getProvince() + "-" +
                                project.getRegion().getCity() +
                                (project.getRegion().getDistrict() != null ? "-" + project.getRegion().getDistrict() : ""));

                        log.info("中标金额: " + project.getAmount() + "万元");
                        log.info("----------------------");

                        b.setTitile(project.getCleanTitle());
//                b.setRole(project.get); //todo 找不到角色
//                b.setType(project.getType()); //招标默认是0，投标是1
                        b.setType("0");
                        b.setTime(project.getPublishDate());

                        list.add(b);

                    });

                    return list;
                }


            }


        return null;
    }


    //解析对应的行政许可
    // 解析方法
    public static LicenseInfo parse3(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(json, LicenseInfo.class);
    }

    // 使用示例
    public static  List<LicVo>  ParseLic(String json) {
//        String json = "您的JSON数据";

    List<LicVo>  infolist=new  ArrayList<LicVo>();

         LicenseInfo  lic=new LicenseInfo();
         
         LicVo l=new LicVo();

        try {
            LicenseInfo info = parse3(json);

            //预处理数据
            if(null ==info){
               log.info("获取License实体是空的");
            }else{

                if(null== info.getLicenses()){
                    log.error("请注意获取License实体为空");
                }else{
                    log.info("许可证总数: " + info.getLicenses().size());

                    log.info("========================");

                    info.getLicenses().forEach(license -> {
                        log.info("许可证名称: " + license.getName());
                        log.info("有效期: " + license.getStartDate() + " 至 " + license.getExpiryDate());
                        log.info("颁发机构: " + license.getAuthority());
                        log.info("审批日期: " + license.getApprovalDate());
                        log.info("--------------------------------");


                        //赋值给vo
                        l.setGov(license.getAuthority());
                        l.setName(license.getName());
                        l.setEnd(license.getExpiryDate());
                        l.setStart(license.getStartDate());
                        l.setContent(license.getContent());
                        l.setName(license.getName());
                        l.setHasPermit("true");

                        infolist.add(l);
                    });
                }

            }


           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return infolist;

    }




    // 解析方法
    public static JudicialCaseResponse parse5(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(json, JudicialCaseResponse.class);
    }

    // 使用示例
    public static   List<CourtAnnouncement>  parseCourt(String  json) {


        List<CourtAnnouncement> list=new ArrayList<>();
           CourtAnnouncement court=null;
        try {
            JudicialCaseResponse response = parse5(json);

            //校验判断
            if(null==response.getData()){
                log.info("请注意改数据是空的");
            }else{
                log.info("案件总数: " + response.getData().size());
//                log.info("最新案件日期: " + response.getData().get(0).getCaseCreateTime());

//            response.getData().forEach(caseInfo -> {
//               log.info("\n案号: " + caseInfo.getCleanCaseNumber());
//               log.info("法院: " + caseInfo.getCourtName());
//               log.info("当事人: ");
//
//
//                caseInfo.getParties().forEach(p ->
//                       log.info(" - " + p.getName() + " (" + p.getType() + ")"));
//                list.add(court);
//            });

                //借助基本解析完成
                for(int k=0;k<response.getData().size();k++){
                    court= new CourtAnnouncement();
                    JudicialCaseResponse.CaseInfo caseInfo;
                    caseInfo=response.getData().get(k);

                    court.setCaseNumber( caseInfo.getCleanCaseNumber());
                    court.setHasAnnouncement(Boolean.TRUE);
                    court.setAnnouncementDate(caseInfo.getCaseCreateTime());
                    court.setAnnouncementType(caseInfo.getType());
                    court.setSessionReason(caseInfo.getSource());
                    court.setSessionDate(caseInfo.getCaseCreateTime()); //开庭日期需要核实

                    list.add(court);
            }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }








        public static int  parseInsevet(String  json) {
//            String json = "{\"stat\":1,\"total\":0,\"page\":[]}";
            JSONObject jsonObject = new JSONObject(json);

            // 直接获取字段值
            int stat = jsonObject.getInt("stat");
//            int total = jsonObject.getInt("total");
            // page 是空数组，可以解析为 JSONArray
           log.info("stat: " + stat);
//           log.info("total: " + total);
//           log.info("page: " + jsonObject.getJSONArray("page"));


//            if (jsonObject.getJSONArray("page").size() == 0) {
//                return 0;
//            }
            return 0;
        }



    public static List<BusinessAbnormality> ParseEception(String  json) {
//        String json = "{\"stat\":1,\"anomalyList\":[{\"removeReason\":\"列入经营异常名录3年内...\",\"createReason\":\"未公示年度报告\",\"sort_key\":\"2015-07-06\",\"createDate\":\"2015-07-06\",\"removeDate\":\"2015-12-17\",\"removeAuthority\":\"江苏省市场监督管理局\",\"source\":\"enterprise\"}],\"name\":\"金盾检测技术股份有限公司\",\"entity_type\":\"enterprise\",\"socialCreditCode\":\"91320000559284761U\",\"legalRepresentative\":\"李云亚\",\"regNumber\":\"320000000090648\",\"_id\":\"57c94f71d57260d2\",\"nameId\":\"57c94f71d57260d2\",\"businessTags\":[\"计算机软硬件销售\",\"安全审计\",\"渗透测试\"]}";

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<BusinessAbnormality> beanlist=new ArrayList<>();
        try {
            EnterpriseAnomalyResponse response = mapper.readValue(json, EnterpriseAnomalyResponse.class);

            // 打印关键信息
            System.out.println("企业名称: " + response.getName());
            System.out.println("统一社会信用代码: " + response.getSocialCreditCode());
            System.out.println("法定代表人: " + response.getLegalRepresentative());



            BusinessAbnormality bean=null;
            // 遍历异常记录
            System.out.println("\n经营异常记录:");
            if(response.getAnomalies()!=null&& response.getAnomalies().size()>0){
                for (AnomalyEntry entry : response.getAnomalies()) {
                    System.out.println("列入日期: " + entry.getCreateDate());
                    System.out.println("移除原因: " + entry.getRemoveReason());
                    System.out.println("移除机关: " + entry.getRemoveAuthority());
                    System.out.println("--------------------");
                    bean = new BusinessAbnormality();
                    bean.setAbnormalityCount( response.getAnomalies().size());
                    bean.setLatestInclusionDate(entry.getRemoveDate());
                    bean.setRemovalReasons(entry.getRemoveAuthority());
                    beanlist.add(bean);
                }



                // 打印业务标签
                System.out.println("\n业务标签:");
                for (String tag : response.getBusinessTags()) {
                    System.out.println("- " + tag);
                }
            }else {
                log.error("失败了");
            }
   

        } catch (Exception e) {
            e.printStackTrace();
        }

        return  beanlist;

    }






    public static    List<TaxpayerQuali>   ParseCert(String json) {
//        String json = "{\"tpQualification\":[{\"begin\":\"2016-05-01\",\"tpName\":\"江苏大峘集团有限公司\",\"end\":\"9999-12-31\",\"qualification\":\"简易办法征收一般纳税人\",\"tpId\":\"320121134754932\"},{\"begin\":\"2005-06-01\",\"tpName\":\"江苏大峘集团有限公司\",\"end\":\"9999-12-31\",\"qualification\":\"增值税一般纳税人\",\"tpId\":\"320121134754932\"}],\"stat\":1,\"total\":2}";

        ObjectMapper mapper = new ObjectMapper();
        List<TaxpayerQuali> list = null;
        try {
            TaxpayerQualificationResponse response = mapper.readValue(json, TaxpayerQualificationResponse.class);


            TaxpayerQuali taxpayerQuali = new TaxpayerQuali();

            list = new ArrayList<>();

            // 输出统计信息
            System.out.println("状态码: " + response.getStat());
            System.out.println("总记录数: " + response.getTotal());
            System.out.println("----------------------");

            // 遍历纳税人资格
            for (TaxpayerQualification qual : response.getQualifications()) {
                taxpayerQuali = new TaxpayerQuali();
                System.out.println("纳税人名称: " + qual.getTaxpayerName());
                System.out.println("资格类型: " + qual.getQualification());
                System.out.println("有效期: " + qual.getBegin() + " 至 " + qual.getEnd());
                System.out.println("----------------------");

                taxpayerQuali.setCertType(qual.getQualification());
                taxpayerQuali.setName(qual.getTaxpayerName());
                taxpayerQuali.setCertType(qual.getQualification());
                list.add(taxpayerQuali);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }




    // JSON解析方法
    public static JudicialExecutionResponse parseExecute(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(json, JudicialExecutionResponse.class);
    }

    // 使用示例
    public static List<ExecutedPerson> pasrsePerson(String json) {
//        String json = "{\"stat\":1,\"total\":1,"
//                + "\"data\":[{\"efExecutiveCourt\":\"南京江北新区人民法院\","
//                + "\"efLimitedPersonName\":\"高立涛\",\"efCaseCreateTime\":\"2025-01-13\","
//                + "\"efCaseNumber\":\"(2025)苏0192执210号\",\"_id\":\"TAwkK9t5pN+Ieg22Gfexxw==\","
//                + "\"nameId\":\"O9QxjZAqBks=\"}]}";

        try {
            JudicialExecutionResponse response = parseExecute(json);


            ExecutedPerson executedPerson=new ExecutedPerson();
            ArrayList list=new ArrayList();

            System.out.println("执行案件总数: " + response.getData().size());
            System.out.println("========================");

            response.getData().forEach(caseInfo -> {
                System.out.println("案号: " + caseInfo.getFormattedCaseNo());
                System.out.println("法院: " + caseInfo.getCourt());
                System.out.println("立案日期: " + caseInfo.getCaseDate());
                System.out.println("受限人: " + caseInfo.getRestrictedPerson());
                System.out.println("案件年份: " + caseInfo.getCaseYear());
                System.out.println("----------------------");
                executedPerson.setCaseNumber(caseInfo.getCaseNumber());
                executedPerson.setFilingDate(caseInfo.getCaseDate());
                executedPerson.setHasExecution(true);
                list.add(executedPerson);
            });

            return  list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }







    }